#include "register_types.h"

#include <gdextension_interface.h>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/godot.hpp>

#include "gd_cpp.h"
#include "gd_node.h"
#include "gd_singleton.h"
#include "server/gd_web_server.h"

using namespace godot;

static GdSingleton *_my_singleton;

void gdcpp_initialize(ModuleInitializationLevel p_level) {
	if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) {
		ClassDB::register_class<GdCpp>();
		ClassDB::register_class<GdNode>();
		ClassDB::register_class<GdSingleton>();
		ClassDB::register_class<GdWebServer>();

		_my_singleton = memnew(GdSingleton);
		Engine::get_singleton()->register_singleton("GdSingleton", GdSingleton::get_singleton());
	}
}

void gdcpp_terminate(ModuleInitializationLevel p_level) {
	if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) {
		Engine::get_singleton()->unregister_singleton("GdSingleton");
		memdelete(_my_singleton);
	}
}

extern "C" {
GDExtensionBool GDE_EXPORT gdcpp_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) {
	godot::GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);

	init_obj.register_initializer(gdcpp_initialize);
	init_obj.register_terminator(gdcpp_terminate);
	init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SCENE);

	return init_obj.init();
}
}
